package com.sensorfriendly.ui;

import java.util.List;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.sensorfriendly.AppConstants;
import com.sensorfriendly.AppContext;
import com.sensorfriendly.R;
import com.sensorfriendly.util.CallUtil;

/**
 * Class for the Settings UI page.
 * @author Jing
 *
 */
public class SettingsActivity extends Activity implements OnClickListener{

	private static final int GALLERY_ID = 0;
	private static final int TTS_CHECK = GALLERY_ID+1;

	private SharedPreferences sharedPrefs;
	private EditText emergencyNumEditText;
	private MyToggleButton audioToggle;
	private MyToggleButton speakToggle;
	private MyToggleButton animateToggle;

	
	/**
	 * Method being called when the UI page is first created. 
	 * We initialize all the UI components as class variables here.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		((TextView) findViewById(R.id.page_title)).setText("Settings");
		((ImageView) findViewById(R.id.ab_settings)).setOnClickListener(this);
		((ImageView) findViewById(R.id.ab_home)).setOnClickListener(this);
		((ImageView) findViewById(R.id.ab_call)).setVisibility(View.GONE);
		
		
		sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		emergencyNumEditText = (EditText) findViewById(R.id.emergency_number_edit);
		
		Button editButton = (Button) findViewById(R.id.edit);
		editButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent editScenariosActivity = new Intent(SettingsActivity.this,EditScenario.class);
				startActivity(editScenariosActivity);
			}
		});

		audioToggle = (MyToggleButton) findViewById(R.id.audio_toggle);
		audioToggle.setOnClickListener(this);
		speakToggle = (MyToggleButton) findViewById(R.id.speak_toggle);
		speakToggle.setOnClickListener(this);
		animateToggle = (MyToggleButton) findViewById(R.id.animation_toggle);
		
		boolean audioActivated = sharedPrefs.getBoolean(
				AppConstants.PREFERENCE_AUDIO_ACTIVATED, true);
		audioToggle.toggle(audioActivated);
		boolean speechoActivated = sharedPrefs.getBoolean(
				AppConstants.PREFERENCE_SPEECH_ACTIVATED, true);
		speakToggle.toggle(speechoActivated);
		animateToggle.toggle(sharedPrefs.getBoolean(AppConstants.PREFERENCE_ANIMATION_ACTIVATED, true));
		
		/*
		 Getting the emergency number if user have entered it before.
		 */
		String emergencyNumber = sharedPrefs.getString(
				AppConstants.PREFERENCE_EMERGENCY_NUMBER, "");
		if (emergencyNumber.length() < 1) {
			emergencyNumEditText.setFocusable(true);
			emergencyNumber = "Emergency contact phone number";
			emergencyNumEditText.setHint(emergencyNumber);
		} else {
			emergencyNumEditText.setText(emergencyNumber);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	/**
	 * commit all the setting changes before user leaves the page
	 */
	@Override
	public void onPause() {
		super.onPause();
		Editor editor = sharedPrefs.edit();
		editor.putBoolean(AppConstants.PREFERENCE_AUDIO_ACTIVATED,
				audioToggle.isActivated());
		editor.putBoolean(AppConstants.PREFERENCE_SPEECH_ACTIVATED,
				speakToggle.isActivated());
		editor.putBoolean(AppConstants.PREFERENCE_ANIMATION_ACTIVATED,
				animateToggle.isActivated());
		
		Pattern phoneNumPattern = Patterns.PHONE;
		String phoneNum = emergencyNumEditText.getText().toString();
		//validating the phone number user entered.
		if (!(phoneNum == null) && phoneNum.length() > 1) {
			if (phoneNumPattern.matcher(phoneNum).matches()) {
				editor.putString(
						AppConstants.PREFERENCE_EMERGENCY_NUMBER,
						phoneNum);
			} else {
				Toast.makeText(this, "Not a valid phone number",
						Toast.LENGTH_LONG).show();
			}
		}
		editor.commit();
	}
	
	
	/**
	 * onClick methods handling clicking event from muliple UI compoents
	 */
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.audio_toggle:
			// check for TTS data to see if device supports text-to-speech.
			Intent checkTTSIntent = new Intent();
			checkTTSIntent
					.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
			startActivityForResult(checkTTSIntent, TTS_CHECK);
			break;
		case R.id.speak_toggle:
			// Check if the device supports speech recognition
			// Toggle between on/off if it does. Stays off if the device does not support 
			// speech recognition.
			PackageManager pm = getPackageManager();
			List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
					RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
			if (activities.size() == 0 || !isOnline()) {
				speakToggle.toggle(false);
			}
			else{
				speakToggle.toggle();
			}
			break;
		
		// Two cases below are for buttons on the action bar.
		case R.id.ab_settings:
			Intent settingsIntent = new Intent(this, SettingsActivity.class);
			startActivity(settingsIntent);
			break;
			
		case R.id.ab_home:
			Intent homeIntent = new Intent(this, DashboardNavigationActivity.class);
			homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(homeIntent);
			break;
		}
		
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case GALLERY_ID:
			if (resultCode == RESULT_OK) {
				Uri selectedImage = data.getData();
				String selectedPath = getPath(selectedImage);
				Editor editor = sharedPrefs.edit();
				if (selectedPath.length()>1) {
					String[]pathNames = selectedPath.split("/");
					StringBuilder sb = new StringBuilder();
					for(int i=0; i<pathNames.length-1; i++){
						sb.append(pathNames[i]);
						sb.append("/");
					}					
				}
			}
			break;
		case TTS_CHECK:
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				audioToggle.toggle();
			} else {
				audioToggle.toggle(false);
			}
		}
	}
	
	/**
	 * Check if the device is connected to the internet
	 * @return true if device is connected to the internet false otherwise.
	 */
	private boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnected()) {
			return true;
		}
		return false;
	}
	
	/*
	 * Getting a complete file path based on a media file Uri.
	 */
	public String getPath(Uri uri) {
	    String selectedImagePath;
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    if(cursor != null){
	        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	        cursor.moveToFirst();
	        selectedImagePath = cursor.getString(column_index);
	    }else{
	        selectedImagePath = null;
	    }

	    if(selectedImagePath == null){
	        selectedImagePath = uri.getPath();
	    }
	    return selectedImagePath;
	}

}
